package com.luoying.itew.fragment;

import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.luoying.itew.R;
import com.luoying.itew.activity.InformationActivity;
import com.luoying.itew.adapter.DetaiImgAdapter;
import com.luoying.itew.bean.CollectData;
import com.luoying.itew.bean.CollectorBean;
import com.luoying.itew.bean.MonitorBean;
import com.luoying.itew.common.Constant;
import com.luoying.itew.event.Detail3DEvent;
import com.luoying.itew.http.HttpRequestUtils;
import com.luoying.itew.http.HttpResponseCallBack;
import com.luoying.itew.manage.UserManage;
import com.luoying.itew.util.ExecutorUtils;
import com.luoying.itew.util.FileUtils;
import com.luoying.itew.util.MonitorUtils;
import com.luoying.itew.util.ThreeDUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Administrator on 2018/5/24.
 * time 2018-5-10
 * author zm
 * 边坡详情界面
 */
public class DetailsFragment extends BaseFragment {
    public static  HashMap<Integer,CollectorBean> hashMap = new HashMap<>();
    public List<CollectorBean> collectBeans = new ArrayList<>();

    @BindView(R.id.detail_name_tv)
    TextView detailNameTv;
    @BindView(R.id.detail_state_tv)
    TextView detailStateTv;
    @BindView(R.id.detail_location_tv)
    TextView detailLocationTv;
    @BindView(R.id.detail_type_tv)
    TextView detailTypeTv;
    @BindView(R.id.detail_height_tv)
    TextView detailHeightTv;
    @BindView(R.id.detail_device_factory_tv)
    TextView detailDeviceFactoryTv;
    @BindView(R.id.detail_suggest_ll)
    LinearLayout detailSuggestLl;
    @BindView(R.id.rc_img_list)
    RecyclerView imgRecyclerView;
    @BindView(R.id.detail_suggest_view)
    View suggest_line;

    //展示数据对象
    private MonitorBean bean;
    //服务端地址
    private String serviceUrl;
    //拼接路径
    private String objPath;
    //3gd文件
    private String path3dUrl;
    //zip文件
    private String objZip;

    private DetaiImgAdapter adapter;
    private List<String> imgList = new ArrayList<>();

    @Override
    protected int getLayoutResId() {
        return R.layout.details_fragment;
    }

    @Override
    protected void init() {
        super.init();
        if (getActivity() != null) {
            bean = UserManage.getInstance().getMonitorById(((InformationActivity) getActivity()).getCuurMonitorId());
        }
        if (bean == null && getContext() != null) {
            Toast.makeText(getContext(), "数据错误", Toast.LENGTH_LONG).show();
            return;
        }
        if(!EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().register(this);
        }
        detailNameTv.setText(bean.getMonitorPointName());
        int state = MonitorUtils.getMonitorState(bean);
        if(bean.getMonitorPointId()==100000003){
            state =  Constant.WARN_LEVEL_GREEN;
        }
        switch (state){
            default:
            case Constant.WARN_LEVEL_GREEN:
                detailSuggestLl.setVisibility(View.GONE);
                suggest_line.setVisibility(View.GONE);
                break;
            case Constant.WARN_LEVEL_YELLOW:
            case Constant.WARN_LEVEL_ORANGE:
                detailDeviceFactoryTv.setText("应密切关注，加强巡查频率");
                suggest_line.setVisibility(View.VISIBLE);
                break;
            case Constant.WARN_LEVEL_RED:
                detailDeviceFactoryTv.setText("应采取安全应急措施");
                suggest_line.setVisibility(View.VISIBLE);
                break;
        }
        String stateStr = String.format("%s,%s", bean.getMonitorStatusDesc(), MonitorUtils.WarnLevelToString(MonitorUtils.getMonitorState(bean)));
        detailStateTv.setText(stateStr);
        detailLocationTv.setText(bean.getMonitorArea().getFullName());
        String typeStr = String.format("%s,%s,%s", bean.getMonitorTypeLabel(),
                bean.getWeakOutDipPlane() == 0 ? getString(R.string.detail_fine_face) : getString(R.string.detail_danger_face),
                bean.getMaterialTypeDesc());
        detailTypeTv.setText(typeStr);

        try {
            BigDecimal bg = new BigDecimal((bean.getMonitorHeight()/1000.0));
            detailHeightTv.setText(String.format(getString(R.string.detail_height_info),bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()+""));
        } catch (Exception e) {
            e.printStackTrace();
        }
        getImgList();
        adapter = new DetaiImgAdapter(imgList,getContext());
    }

    /**
     * 获取监测点3d详细信息
     */
    public void getMoitor3DInfo() {
        Toast.makeText(getContext(), "文件开始下载,请稍等", Toast.LENGTH_LONG).show();
        HttpRequestUtils.getInstance().get3dInfoDetai(bean.getMonitorPointId() + "", new HttpResponseCallBack<JsonObject>() {
            @Override
            public void onFail(String message) {
                Toast.makeText(getContext(), message, Toast.LENGTH_LONG).show();
            }

            @Override
            public void onSuccess(JsonObject data) {
                if (data == null) {
                    Toast.makeText(getContext(), "网络连接错误", Toast.LENGTH_LONG).show();
                    return;
                }
                serviceUrl = data.get("fileServerUri").getAsString();
                objPath = data.getAsJsonObject("monitorPoint").get("objPathApp").getAsString();
                path3dUrl = data.getAsJsonObject("monitorPoint").get("g3dbFileApp").getAsString();
                objZip = data.getAsJsonObject("monitorPoint").get("objZipFileApp").getAsString();
                try {
                    JSONObject jsonObject = new JSONObject(data.toString());
                    ThreeDUtils.setModel(jsonObject);
                    ThreeDUtils.setRatio(data.getAsJsonObject("monitorPoint").get("ratio").getAsFloat());
                    JSONArray jsonArray = jsonObject.getJSONObject("monitorPoint").getJSONArray("allCollectors");
                    collectBeans = new Gson().fromJson(jsonArray.toString(),new TypeToken<List<CollectorBean>>(){}.getType());
                } catch (JSONException e) {
                    Toast.makeText(getContext(), "网络连接错误", Toast.LENGTH_LONG).show();
                    e.printStackTrace();
                }
                File baseFile = new File(FileUtils.getBasePath() + objPath);
                if (!baseFile.exists()) {
                    baseFile.mkdirs();
                }
                //3D文件
                File file3D = new File(baseFile, path3dUrl);
                String url3d = serviceUrl + objPath + "/" + path3dUrl;
                if (!file3D.exists()) {
                    try {
                        file3D.createNewFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                        Toast.makeText(getActivity(), "文件下载失败", Toast.LENGTH_LONG).show();
                        return;
                    }
                }
                downFile(url3d, file3D, false);
            }

            @Override
            public void onError(String message) {
                Toast.makeText(getContext(), "网络连接错误", Toast.LENGTH_LONG).show();
            }
        });
    }

    /**
     * 3d模型的采集器数据
     */
    public void getCollectorList() {
        HttpRequestUtils.getInstance().getCollectorList(bean.getMonitorPointId() , new HttpResponseCallBack<JsonObject>() {
            @Override
            public void onFail(String message) {
                Toast.makeText(getContext(), message, Toast.LENGTH_LONG).show();
            }

            @Override
            public void onSuccess(JsonObject data) {
                try {
                    JsonArray  jsonElements = data.getAsJsonArray("collectorDatas");
                    List<CollectData> collectDataList = new Gson().fromJson(jsonElements.toString(),new TypeToken<List<CollectData>>(){}.getType());

                    for (CollectorBean collectBean : collectBeans) {
                        hashMap.put(collectBean.getCollectorId(),collectBean);
                    }
                    for (CollectData collectData : collectDataList) {
                        if(hashMap.containsKey(Integer.valueOf(collectData.getCollectorId()))){
                          MonitorUtils.bindColletrDate(hashMap.get(Integer.valueOf(collectData.getCollectorId())),collectData);
                        }
                    }
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(String message) {
                Toast.makeText(getContext(), "网络连接错误", Toast.LENGTH_LONG).show();
            }
        });
    }

    /**
     * 获取监测点图片
     */
    public void getImgList(){
        HttpRequestUtils.getInstance().getImgList(bean.getMonitorPointId() , new HttpResponseCallBack<Map<String,String>>() {
            @Override
            public void onFail(String message) {
            }

            @Override
            public void onSuccess(Map<String,String> data) {
                imgList.clear();
                if(data.containsKey("monitorPointImageUrl")){
                    imgList.add(data.get("monitorPointImageUrl"));
                }
                if(data.containsKey("planeImageUrl")){
                    imgList.add(data.get("planeImageUrl"));
                }
                if(data.containsKey("orbitImageUrl")){
                    imgList.add(data.get("orbitImageUrl"));
                }
                if(data.containsKey("aerialImageUrl")){
                    imgList.add(data.get("aerialImageUrl"));
                }

                if(imgList.isEmpty()){
                    imgRecyclerView.setVisibility(View.GONE);
                    return;
                }
                if (imgRecyclerView.getLayoutManager()==null) {
                    imgRecyclerView.setLayoutManager(new GridLayoutManager(getContext(),2));
                }
                if(imgRecyclerView.getAdapter()==null){
                    imgRecyclerView.setAdapter(adapter);
                }
                imgRecyclerView.setHasFixedSize(true);
                imgRecyclerView.setNestedScrollingEnabled(false);
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onError(String message) {
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(Detail3DEvent event) {
        if (!event.isSuucess) {
            Toast.makeText(getActivity(), "文件下载失败", Toast.LENGTH_LONG).show();
            return;
        }
        String file = event.fileName;
        if (TextUtils.isEmpty(objZip)) {
            goModelActivity();
            return;
        }
        if (file.equals(path3dUrl)) {
            //开始下载zip文件
            String urlZip = serviceUrl + objPath + File.separatorChar + objZip;
            File zipFile = new File(FileUtils.getBasePath() + objPath, objZip);
            if (!zipFile.exists()) {
                try {
                    zipFile.createNewFile();
                } catch (IOException e) {
                    Toast.makeText(getActivity(), "文件下载失败", Toast.LENGTH_LONG).show();
                    e.printStackTrace();
                }
            }
            downFile(urlZip, zipFile, true);
            return;
        } else {
            goModelActivity();
        }
    }

    public void goModelActivity() {
        getCollectorList();
    }

    /**
     * 下载文件
     *
     * @param url
     */
    public void downFile(String url, final File file, final boolean isZip) {
        HttpRequestUtils.getInstance().downFile(url, new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, final Response<ResponseBody> response) {
                if (response == null || !response.isSuccessful() || response.body() == null) {
                    Toast.makeText(getActivity(), "文件下载失败", Toast.LENGTH_LONG).show();
                    return;
                }
                ExecutorUtils.getExecutorService().execute(new Runnable() {
                    @Override
                    public void run() {
                        Detail3DEvent event = new Detail3DEvent();
                        event.fileName = file.getName();
                        try {
                            FileUtils.saveFile(response.body().byteStream(), file);
                            if (isZip) {
                                FileUtils.unzip(file, file.getParentFile());
                            }
                            event.isSuucess = true;
                        } catch (Exception e) {
                            event.isSuucess = false;
                        }
                        EventBus.getDefault().post(event);
                    }
                });
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Toast.makeText(getActivity(), "文件下载失败", Toast.LENGTH_LONG).show();
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

}
